package com.liuh.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;

/**
 * @note 用户登陆验证过滤器
 * @author liuh
 * @date 2021年4月26日 下午4:55:11
 */
public class LoginValidate implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		Object obj = httpRequest.getSession().getAttribute("loginName");
		if (obj == null) {
			// 未登陆
			if (isAjaxRequest(httpRequest)) {
				ServletUtil.write(httpResponse, JSONUtil.toJsonPrettyStr(OutMsg.noLogin()),
						"application/json;charset=UTF-8");
			} else {
				httpResponse.sendRedirect("login.jsp");
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	/**
	 * @note 是否Ajax 请求
	 * @author liuh
	 * @date 2019年7月28日 下午5:03:26
	 */
	private static boolean isAjaxRequest(HttpServletRequest request) {
		String accept = request.getHeader("accept");
		if (accept != null && accept.indexOf("application/json") != -1) {
			return true;
		}

		if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
				|| request.getParameter("ajax") != null) {
			return true;
		}
		return false;
	}

}
